package nacos

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/model"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
)

// 链接
func GetNaCosClient() (constant.ClientConfig, []constant.ServerConfig) {
	fmt.Println(viper.GetString("namespace_id"))
	return *constant.NewClientConfig(
			constant.WithNamespaceId(viper.GetString("namespace_id")),  //命名空间
			constant.WithTimeoutMs(viper.GetUint64("with_timeout_ms")), //响应时间
			constant.WithNotLoadCacheAtStart(true),
			constant.WithLogDir("./tmp/nacos/log"),
			constant.WithCacheDir("./tmp/nacos/cache"),
			constant.WithLogLevel("debug"),
		), []constant.ServerConfig{
			*constant.NewServerConfig(viper.GetString("ip_addr"), viper.GetUint64("port"),
				constant.WithScheme("http"), constant.WithContextPath("/nacos")),
		}
}

// nacos 配置信息
func GetNaCosInfo() (string, error) {
	cc, sc := GetNaCosClient()
	client, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)
	if err != nil {
		panic("nacos 链接失败")
	}
	//获取配置
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: viper.GetString("data_id"), //dataID
		Group:  viper.GetString("group")},  //分组
	)
	fmt.Println("nacos配置信息：：：", content)
	return content, err
}

// 创建一个服务注册client
func NewNamingClient() (naming_client.INamingClient, error) {
	cc, sc := GetNaCosClient()
	return clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)
}

// 服务注册
func RegisterServiceInstance(ip, ServiceName, GroupName string, port int64) (bool, error) {
	fmt.Println("注册服务：：", ip, ServiceName, port)
	client, err := NewNamingClient()
	if err != nil {
		return false, nil
	}
	return client.RegisterInstance(vo.RegisterInstanceParam{
		Ip:          ip,
		Port:        uint64(port),
		Enable:      true,
		Healthy:     true,
		ServiceName: ServiceName,
		GroupName:   GroupName,
		Weight:      1,
	})
}

// 服务发现
func GetService(ServiceName, GroupName string) (model.Service, error) {
	client, err := NewNamingClient()
	if err != nil {
		return model.Service{}, nil
	}
	return client.GetService(vo.GetServiceParam{
		Clusters:    nil,
		ServiceName: ServiceName,
		GroupName:   GroupName,
	})
}

// 服务发现 一个健康的实例
func SelectOneHealthyInstance(ServiceName, GroupName string) (string, error) {
	client, err := NewNamingClient()
	if err != nil {
		return "", nil
	}
	fmt.Println("接收参数：：", ServiceName, GroupName)
	fmt.Println(ServiceName)
	fmt.Println(GroupName)
	instance1, err := client.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
		ServiceName: ServiceName,
		GroupName:   GroupName,
	})
	if err != nil {
		return "", err
	}
	fmt.Println("发现的健康服务：", instance1)
	addr := fmt.Sprintf("%v:%d", &instance1.Ip, &instance1.Port)
	//return addr, nil
	return addr, nil
}
